﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"

void QueueInit(Queue* pq)
{
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

// ⼊队列，队尾
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);
	QueueNode* newNode = (QueueNode*)malloc(sizeof(QDataType));
	if (newNode == NULL)
	{
		perror("malloc fail!");
		exit(-1);
	}
	newNode->data = x;
	newNode->next = NULL;
	if (pq->ptail == NULL)
	{
		pq->phead = pq->ptail = newNode;
	}
	else
	{
		pq->ptail->next = newNode;
		pq->ptail = newNode;
	}
	pq->size++;
}

// 出队列，队头
void QueuePop(Queue* pq)
{
	assert(pq && !QueueEmpty(pq));
	//只有一个节点的情况，避免ptail变成野指针
	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else
	{
		//删除队头元素
		QueueNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	pq->size--;
}

//队列判空
bool QueueEmpty(Queue* pq)
{
	return pq->size == 0;
}

//取队头数据
QDataType QueueFront(Queue* pq)
{
	assert(pq && pq->phead);
	return pq->phead->data;
}

//取队尾数据
QDataType QueueBack(Queue* pq)
{
	assert(pq && pq->ptail);
	return pq->ptail->data;
}

//队列有效元素个数
int QueueSize(Queue* pq)
{
	return pq->size;
}

//销毁队列
void QueueDestroy(Queue* pq)
{
	assert(pq);
	QueueNode* cur = pq->phead;
	while (cur != NULL)
	{
		QueueNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}